/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package sa4w.interfaces;

import java.util.ArrayList;

/**
 *
 * @author Leonardo Oliveira Moreira
 * 
 */
public class Response {

    private ArrayList<String> messages;
    private ArrayList<String> errorMessages;
    private boolean reason;
    private String aditionalJson = "";
    
    public Response() {
        messages = new ArrayList<String>();
        errorMessages = new ArrayList<String>();
        reason = false;
    }

    public ArrayList<String> getErrorMessages() {
        return errorMessages;
    }

    public ArrayList<String> getMessages() {
        return messages;
    }

    public boolean isReason() {
        return reason;
    }

    public void setReason(boolean reason) {
        this.reason = reason;
    }

    public void addMessage(String message) {
        message = message.replaceAll("\n+", "");
        message = message.replaceAll("\"", "");
        messages.add(message);
    }
    
    public void addErrorMessage(String message) {
        message = message.replaceAll("\n+", "");
        message = message.replaceAll("\"", "");
        errorMessages.add(message);
    }
    
    public String toJSON() {
        StringBuilder sb = new StringBuilder();
        
        sb.append("{");
        sb.append("\"reason\":\"" + reason + "\",");
        sb.append("\"messages\":[");
        for (int i = 0; messages != null && i < messages.size(); i++) {
            if (messages.get(i).trim().length() > 0) {
                sb.append("{");
                sb.append("\"message\":\"" + messages.get(i).replaceAll("\"", "'") + "\"");            
                sb.append("},");
            }
        }
        if (sb.toString().substring(sb.length() - 1, sb.length()).equals(","))
            sb = new StringBuilder(sb.substring(0, sb.length() - 1));
        sb.append("],");
        sb.append("\"errorMessages\":[");
        for (int i = 0; errorMessages != null && i < errorMessages.size(); i++) {
            if (errorMessages.get(i).trim().length() > 0) {
                sb.append("{");
                sb.append("\"errorMessage\":\"" + errorMessages.get(i).replaceAll("\"", "'") + "\"");
                sb.append("},");
            }
        }        
        if (sb.toString().substring(sb.length() - 1, sb.length()).equals(","))
            sb = new StringBuilder(sb.substring(0, sb.length() - 1));        
        sb.append("]");
        if (aditionalJson.trim().length() > 0)
            sb.append("," + aditionalJson);
        sb.append("}");
        return sb.toString();
    }
    
    public void addAditionalJson(String json) {
        aditionalJson = json;
    }
}
